package com.zjj.lbw.spring6.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
class SpringSecurityConfiguration3 {

    @Bean
    public UserDetailsService userDetailsService(SecurityProperties properties, ObjectProvider<PasswordEncoder> passwordEncoder) {
        return new InMemoryUserDetailsManager(
                User.withUsername("13888888888").password("{noop}123").roles("ADMIN").build(),          // ROLE_ADMIN
                User.withUsername("13777777777").password("{noop}123").roles("USER").build(),           // ROLE_USER
                User.withUsername("13666666666").password("{noop}123").authorities("WRITE").build()     // WRITE
        );
    }

    @Bean
    public RoleHierarchy roleHierarchy() {
        return RoleHierarchyImpl.fromHierarchy("ROLE_ADMIN > ROLE_USER");
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.authorizeHttpRequests(request -> request
                .requestMatchers("/private").authenticated()
                .requestMatchers("/public").hasAnyRole("USER")            // 判断有没有 ROLE_USER
                .requestMatchers("/delete").hasRole("ADMIN")            // 判断有没有 ROLE_ADMIN
                .requestMatchers("/write").hasAuthority("WRITE")        // 判断有没有 WRITE
                .anyRequest().permitAll());
        httpSecurity.formLogin(Customizer.withDefaults());
        httpSecurity.csrf(AbstractHttpConfigurer::disable);

        return httpSecurity.build();
    }
}
